import request from '@/util/request.ts'

// 定义接口类型
export interface RoleData {
  id?: number
  name: string
  code: string
  description: string
  createTime?: string
  updateTime?: string
}

export interface RoleResponseData {
  code: number
  data: {
    records: RoleData[]
    total: number
    msg: string
  }
}
export interface Permission {
  id: number
  name: string
  code: string
  description: string
  createTime: number[] // [年, 月, 日, 时, 分, 秒]
  updateTime: number[]
}
export interface PermissionResponseData {
  allPermissions: Permission[]
  checkedPermissions: Permission[] // 前端需要手动 .map(p => p.id) 提取 ID
}

export interface MenuResponseData {
  code: number
  msg: string
  data: PermissionResponseData
  total?: number
}

enum API {
  AllROLE = '/admin/role/page',
  AddOrUpdateRole = '/admin/role',
  RemoveRole = '/admin/role',
  AllMenuList = '/admin/role/permissions',
  SetPermission = '/admin/role/assignPermissions',
}

// 获取所有角色列表
export const reqAllRoleList = (page: any, limit: any, roleName: any) =>
  request.get<any, RoleResponseData>(
    `${API.AllROLE}?page=${page}&pageSize=${limit}&name=${roleName}`,
  )

// 添加或更新角色
export const reqAddOrUpdateRole = async (role: RoleData) => {
  const method = role.id ? 'put' : 'post'
  return request[method]<any, any>(API.AddOrUpdateRole, role)
}

// 删除角色
export const reqRemoveRole = async (id: number) => {
  return request.delete<any, any>(`${API.RemoveRole}/${id}`)
}

// 获取角色的所有菜单列表
export const reqAllMenuList = async (roleId: number) => {
  return request.get<any, MenuResponseData>(`${API.AllMenuList}/${roleId}`)
}

// 设置角色权限
export const reqSetPermission = async (
  roleId: number,
  permissionIds: number[],
) => {
  return request.post<any, any>(API.SetPermission, {
    roleId,
    permissionIds,
  })
}
